package com.nuanshui.heatedloan.entity.cms.security;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.nuanshui.heatedloan.entity.IdEntity;

/**
 * 模块
 */
@Entity
@Table(name = "cms_security_module")
public class Module extends IdEntity implements Comparable<Module> {

	/**
	 * 模块名称
	 */
	@Column(nullable = false, length = 32)
	private String name;

	/**
	 * 模块的入口地址
	 */
	@Column(nullable = false, length = 255)
	private String url;

	/**
	 * 描述
	 */
	@Column(length = 255)
	private String description;

	/**
	 * 授权名称（类似module:save）<br>
	 * 查看/管理这个模块需要的权限
	 */
	@Column(nullable = false, length = 32)
	private String sn;

	/**
	 * 模块的排序号,越小优先级越高
	 */
	@Column(length = 2)
	private Integer priority = 99;

	@JsonIgnore
	@JSONField(serialize=false)
	@ManyToOne
	@JoinColumn(name = "parentId")
	private Module parent;

	@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "parent")
	@OrderBy("priority ASC")
	private List<Module> children = Lists.newArrayList();

	public String getName() {
		return name;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(final String url) {
		this.url = url;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(final String description) {
		this.description = description;
	}

	public Integer getPriority() {
		return priority;
	}

	public void setPriority(final Integer priority) {
		this.priority = priority;
	}

	public Module getParent() {
		return parent;
	}

	public void setParent(final Module parent) {
		this.parent = parent;
	}

	public List<Module> getChildren() {
		return children;
	}

	public void setChildren(final List<Module> children) {
		this.children = children;
	}

	public String getSn() {
		return sn;
	}

	public void setSn(final String sn) {
		this.sn = sn;
	}

	@Override
	public int compareTo(final Module m) {
		if (m == null) {
			return -1;
		} else if (m == this) {
			return 0;
		} else if (this.priority < m.getPriority()) {
			return -1;
		} else if (this.priority > m.getPriority()) {
			return 1;
		}

		return 0;
	}

	@Override
	public String toString() {
		return Objects.toStringHelper(this).addValue(id).addValue(name)
				.addValue(parent == null ? null : parent.getName())
				.addValue(children.size()).toString();
	}

}
